require('es6-promise').polyfill();
require('isomorphic-fetch');
import config  from '../config';
import EXIF from 'exif-js';

// export function get(url,data) {
//     var request = '';
//     if (data) {
//         for (let k in data) {
//             request += (k + "=" + data[k] + "&");
//         }
//         request = request.substring(0,request.length-1);
//     }
//     var promise = new Promise(function(resolve, reject){
//         var client = new XMLHttpRequest();
//         client.open("GET", config.SERVICE_URL + url + '?' + request, true);
//         client.onreadystatechange = handler;
//         client.responseType = "json";
//         client.setRequestHeader("Accept", "application/json");
//         client.send();
//         function handler() {
//             if (this.readyState !== 4) {
//                 return;
//             }
//             if (this.status === 200) {
//                 resolve(this.response);
//             } else {
//                 reject(new Error(this.statusText));
//             }
//         }
//     });
//     return promise;
// }
// export function post(url,data) {
//     var request = '';
//     if (data) {
//         for (let k in data) {
//             request += (k + "=" + data[k] + "&");
//         }
//         request = request.substring(0,request.length-1);
//     }
//     var promise = new Promise(function(resolve, reject){
//         var client = new XMLHttpRequest();
//         client.open("POST", config.SERVICE_URL + url);
//         client.onreadystatechange = handler;
//         client.responseType = "json";
//         client.setRequestHeader("Accept", "application/json");
//         // client.setRequestHeader("Content-Type","application/json; charset=utf-8;");
//         client.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8;");
//         client.setRequestHeader("accesstoken",getItem('token'));
//         client.send(encodeURI(request));
//         function handler() {
//             if (this.readyState !== 4) {
//                 return;
//             }
//             if (this.status === 200) {
//                 resolve(this.response);
//             } else {
//                 reject(new Error(this.statusText));
//             }
//         }
//     });
//     return promise;
// }

// 为fetch添加超时
let oldFetch = fetch; //拦截原始的fetch方法
window.fetch = function (input, opts) {//定义新的fetch方法，封装原有的fetch方法
    var fetchPromise = oldFetch(input, opts);
    var timeoutPromise = new Promise(function (resolve, reject) {
        setTimeout(() => {
            reject(new Error("请求超时"));
            // alert("请求超时,请检查网络")
        }, 10000)
    });
    return Promise.race([fetchPromise, timeoutPromise])
};

export function get(url, data) {
    var request = '';
    if (data) {
        for (let k in data) {
            request += (k + "=" + data[k] + "&");
        }
        request = request.substring(0, request.length - 1);
    }
    return fetch(config.SERVICE_URL + url + '?' + request, {
        method: 'GET',
        // credentials: 'include', // omit: 默认值，忽略cookie的发送 same-origin: cookie只能同域发送 include: cookie既可以同域发送，也可以跨域发送
    }).then((res) => {
            if (res.ok) {
                return res.json()
            } else {
                console.error('请求失败，状态码为：' + res.status)
            }
        }
    ).catch(error => {
        throw error
    })
}

export function post(url, data) {
    let headers = new Headers();
    headers.append("Accept", "application/json,text/plain,*/*");
    headers.append("Content-Type", "application/x-www-form-urlencoded; charset=utf-8;");
    headers.append("accesstoken", getItem('token'));
    let request = '';
    for (let k in data) {
        request += (k + "=" + data[k] + "&");
    }
    request = request.substring(0, request.length - 1);
    return fetch(config.SERVICE_URL + url, {
        method: 'POST',
        // credentials: 'include',
        headers: headers,
        body: encodeURI(request)
    }).then((res) => {
            if (res.ok) {
                return res.json()
            } else {
                console.error('请求失败，状态码为：' + res.status)
            }
        }
    ).catch(error => {
        throw error
    })
}

export function onEnter(nextState, replace) {
    let token = getItem('token');
    let openid = getItem('openid');
    if (!token || !openid) {
        setItem("NEXT_URL", nextState.location.pathname);
        window.location.href = config.SERVICE_URL + '/api/wechat/authorize?url=' + escape(config.JUMP_URL + '/#/login');
        // replace('/login?nextUrl=' + nextState.location.pathname);
    }
}

// export function formatDateLeave(s) {
//     var time = parseInt(s) + "秒";
//     if (parseInt(s) > 60) {
//         var second = parseInt(s) % 60;
//         var min = parseInt(s / 60);
//         time = min + "分" + second + "秒";
//         if (min > 60) {
//             min = parseInt(s / 60) % 60;
//             var hour = parseInt(parseInt(s / 60) / 60);
//             time = hour + "小时" + min + "分" + second + "秒";
//             if (hour > 24) {
//                 hour = parseInt(parseInt(s / 60) / 60) % 24;
//                 var day = parseInt(parseInt(parseInt(s / 60) / 60) / 24);
//                 time = day + "天" + hour + "小时" + min + "分" + second + "秒";
//             }
//         }
//     }
//     return time;
// }
export function formatDateLeave(s) {
    var time = parseInt(s) + "秒";
    if (parseInt(s) > 60) {
        var second = parseInt(s) % 60;
        var min = parseInt(s / 60);
        time = min + "分" + second + "秒";
        if (min > 60) {
            min = parseInt(s / 60) % 60;
            var hour = parseInt(parseInt(s / 60) / 60);
            time = hour + "小时" + min + "分";
            if (hour > 24) {
                hour = parseInt(parseInt(s / 60) / 60) % 24;
                var day = parseInt(parseInt(parseInt(s / 60) / 60) / 24);
                time = day + "天";
            }
        }
    }
    return time;
}

export function formatDate(timeStamp, hourFlag = false, joiner = '-') {
    var time = new Date(timeStamp),
        year = time.getFullYear(),
        month = time.getMonth() + 1,
        date = time.getDate(),
        hour = time.getHours(),
        minute = time.getMinutes();

    return hourFlag ? year + joiner + (month < 10 ? '0' + month : month) + joiner + (date < 10 ? '0' + date : date) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute) : year + joiner + (month < 10 ? '0' + month : month) + joiner + (date < 10 ? '0' + date : date);
}

export function formatDateBetween(timeStampStart, timeStampEnd, noYear) {
    const joiner = '-';
    let time1 = new Date(timeStampStart),
        time2 = new Date(timeStampEnd);
    let year1 = time1.getFullYear(),
        month1 = time1.getMonth() + 1,
        date1 = time1.getDate(),
        hour1 = time1.getHours(),
        minute1 = time1.getMinutes();
    let year2 = time2.getFullYear(),
        month2 = time2.getMonth() + 1,
        date2 = time2.getDate(),
        hour2 = time2.getHours(),
        minute2 = time2.getMinutes();
    let oneDay = (year1 === year2) && (month1 === month2) && (date1 === date2);

    return oneDay ? (
        (noYear ? '' : (year1 + joiner)) + (month1 < 10 ? '0' + month1 : month1) + joiner + (date1 < 10 ? '0' + date1 : date1) + ' ' + (hour1 < 10 ? '0' + hour1 : hour1) + ':' + (minute1 < 10 ? '0' + minute1 : minute1) + '~' + (hour2 < 10 ? '0' + hour2 : hour2) + ':' + (minute2 < 10 ? '0' + minute2 : minute2)
    ) : (
        (noYear ? '' : (year1 + joiner)) + (month1 < 10 ? '0' + month1 : month1) + joiner + (date1 < 10 ? '0' + date1 : date1) + ' ' + (hour1 < 10 ? '0' + hour1 : hour1) + ':' + (minute1 < 10 ? '0' + minute1 : minute1) + '~' +
        (noYear ? '' : (year2 + joiner)) + (month2 < 10 ? '0' + month2 : month2) + joiner + (date2 < 10 ? '0' + date2 : date2) + ' ' + (hour2 < 10 ? '0' + hour2 : hour2) + ':' + (minute2 < 10 ? '0' + minute2 : minute2)
    );
}

export function formatDateWithCh(timeStamp) {
    var time = new Date(timeStamp),
        year = time.getFullYear(),
        month = time.getMonth() + 1,
        date = time.getDate(),
        hour = time.getHours(),
        minute = time.getMinutes();
    return year + '年' + (month < 10 ? '0' + month : month) + '月' + (date < 10 ? '0' + date : date) + '日';
}

export function getChartData(data, yName) {
    let today = formatDate(new Date().getTime());
    let todayStamp = new Date(today).getTime();
    let day = 1000 * 60 * 60 * 24;
    let day90 = 90 * day;
    let ago90 = todayStamp - day90;
    let timestamp = todayStamp;
    let newData = [];
    let i = 0;
    while (timestamp > ago90) {
        let dateStr = formatDate(timestamp).substring(5, 10);
        // newData[dateStr] = data[i++];
        let obj = {};
        obj.name = dateStr;
        obj[yName] = data[i++];
        newData.push(obj);
        timestamp -= day;
    }
    return newData;
    // data.map((item,index)=>{
    //     let day = formatDate(item.publishTime);
    //     if(newData[day]!==undefined){
    //         newData[day] = newData[day] + 1;
    //     }
    // });
    //
    // let proData = [];
    // for(let key in newData){
    //     let obj = {};
    //     obj.name = key.substring(5, 10);
    //     obj[yName] = newData[key];
    //     proData.push(obj);
    // }
    // return proData;
}

export function addNum(num1, num2) {
    var sq1, sq2, m;
    try {
        sq1 = num1.toString().split(".")[1].length;
    } catch (e) {
        sq1 = 0;
    }
    try {
        sq2 = num2.toString().split(".")[1].length;
    } catch (e) {
        sq2 = 0;
    }
    m = Math.pow(10, Math.max(sq1, sq2));
    return ( num1 * m + num2 * m ) / m;
}

export function divideNum(num1, num2) {
    return (num1 / num2 * 100).toFixed();
}

export function strEllipsis(str, length) {
    return str.length > length ? str.substring(0, length) + "..." : str
}

export function minusNum(num1, num2) {
    var sq1, sq2, m;
    try {
        sq1 = num1.toString().split(".")[1].length;
    } catch (e) {
        sq1 = 0;
    }
    try {
        sq2 = num2.toString().split(".")[1].length;
    } catch (e) {
        sq2 = 0;
    }
    m = Math.pow(10, Math.max(sq1, sq2));
    return ( num1 * m - num2 * m ) / m;
}

export function getItem(key) {
    var item = localStorage.getItem(key);
    return !!item ? JSON.parse(item) : null;
}

export function setItem(key, item) {
    localStorage.setItem(key, JSON.stringify(item));
}

export function getSessionItem(key) {
    var item = sessionStorage.getItem(key);
    return !!item ? JSON.parse(item) : null;
}

export function setSessionItem(key, item) {
    sessionStorage.setItem(key, JSON.stringify(item));
}


export const loadState = key => {
    try {
        const serializedState = localStorage.getItem(key);
        if (serializedState === null) {
            return undefined;
        }
        return JSON.parse(serializedState)
    } catch (err) {
        return undefined;
    }
};

export const saveState = (key, state) => {
    try {
        const serializedState = JSON.stringify(state);
        localStorage.setItem(key, serializedState);
    } catch (err) {
        //ignore errors.
    }
};

export function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = $chars.length;
    var pwd = '';
    for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

export function throttle(fn, interval) {
    var self = fn,
        _this = this,
        timer,
        firstTime = true;

    return function () {
        var args = arguments;

        if (firstTime) {
            self.apply(_this, args);
            return firstTime = false;
        }
        if (timer) {
            return false;
        }

        timer = setTimeout(function () {
            clearTimeout(timer);
            timer = null;
            self.apply(_this, args);
        }, interval || 500);
    }
}

export function getClassTarget(event, property) {
    var t = event.target,
        p = property,
        end = this || document.body;
    if (t === end) {
        return t.classList.contains(p) ? t : null;
    }
    while (t && (t !== end)) {
        if (t.classList.contains(p)) {
            return t;
        } else {
            t = t.parentNode;
        }
    }
    return null;

}

export function isSafari() {
    var userAgent = navigator.userAgent;
    return userAgent.indexOf('Safari') > -1;
}

export function isIOS() {
    var userAgent = navigator.userAgent;
    return !!userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
}

export function isCWBrowser() {
    var userAgent = navigator.userAgent;
    return userAgent.indexOf('CWBrowser') > -1;
}

export function isAndroid() {
    var userAgent = navigator.userAgent;
    return userAgent.indexOf('Android') > -1 || userAgent.indexOf('Adr') > -1;
}

export function isQQ() {
    var userAgent = navigator.userAgent;
    return userAgent.match(/QQ\//i) == "QQ/";
}

export function isWeiXin() {
    var userAgent = window.navigator.userAgent.toLowerCase();
    return userAgent.match(/MicroMessenger/i) == 'micromessenger'
}

export function transformToBinaryArr(no) {
    return Number(no).toString(2).split('').map(item => Number(item));
}

export function validateImageUrl(url) {
    return url.indexOf('http://') > -1 || url.indexOf('https://') > -1;
}

export function isLocalStorageSupported() {
    var testKey = 'test',
        storage = window.sessionStorage;
    try {
        storage.setItem(testKey, 1);
        storage.removeItem(testKey);
        return true;
    } catch (error) {
        return false;
    }
}

/**
 * 上传七牛云
 * @param previewCb
 * @param uploadCb
 * TODO 短时间不重复获取TOKEN
 */
export function upload(previewCb, uploadCb) {
    post('/api/qiniu/token').then(function (res) {
        if (res.code === 20000) {
            upLoadFile(res.data.token);
        } else {
            alert(res.code.message);
        }
    });

    function upLoadFile(token) {
        var file = document.getElementsByClassName('imgFile')[0].files[0];
        var Orientation;
        EXIF.getData(file, function () {
            Orientation = EXIF.getTag(this, 'Orientation');
            console.log("照片方向" + Orientation);
        });
        if (!/\/(?:jpeg|png|gif)/i.test(file.type)) {
            alert('图片格式有误');
            return;
        }
        var maxsize = 100 * 1024;
        
        // 获取图片大小
        var userImgSize = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
        console.log("用户图片 : " + userImgSize);
        var reader = new FileReader();
        reader.onload = function () {
            var result = this.result;
            var img = new Image();
            img.src = result;

            // 如果图片大小小于200kb，则直接上传
            // if (result.length <= maxsize) {
            //     img = null;
            //     doUploadFile("http://jingcai-test.oss-cn-shanghai.aliyuncs.com", sendDate, file);
            //     return;
            // }

            // 图片加载完毕之后进行压缩，然后上传
            if (img.complete) {
                callback();
            } else {
                img.onload = callback;
            }

            function callback() {
                var file = transmitCode(compress(img));
                ajaxUpload(config.QINIU_URL, token, file);
                img = null;
            }

        };
        // 读取文件内容
        reader.readAsDataURL(file);

        function ajaxUpload(url, token, file) {
            var formData = new FormData();
            formData.append("file", file);
            // formData.append('key', key);
            formData.append('token', token);
            var oReq = new XMLHttpRequest();
            //上传进度监听
            oReq.upload.onprogress = function (e) {
                // if (e.type == 'progress') {
                //     var percent = Math.round(e.loaded / e.total * 100, 2) + '%';
                //     // console.log(percent);
                //     if (progressCb) {
                //         progressCb(percent);
                //     }
                // }
            };
            //上传结果
            oReq.onreadystatechange = function (e) {
                if (oReq.readyState == 4) {
                    if (oReq.status == 200) {
                        var response = JSON.parse(oReq.response);
                        uploadCb(response);
                    } else {
                        alert('图片上传失败');
                    }
                }
            };
            oReq.open("POST", url);
            oReq.send(formData);
        }


        // 用于压缩图片的canvas
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext('2d');


        // 瓦片canvas
        var tCanvas = document.createElement("canvas");
        var tctx = tCanvas.getContext("2d");

        /**
         * 图片压缩
         * @param img
         * @returns {string}
         */
        function compress(img) {
            var initSize = img.src.length;
            var width = img.width;
            var height = img.height;

            //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
            var ratio;
            if ((ratio = width * height / 4000000) > 1) {
                ratio = Math.sqrt(ratio);
                width /= ratio;
                height /= ratio;
            } else {
                ratio = 1;
            }

            switch (Orientation) {
                case 5:
                case 6:
                case 7:
                case 8:
                    canvas.width = height;
                    canvas.height = width;
                    break;
                default:
                    canvas.width = width;
                    canvas.height = height;
            }

            switch (Orientation) {
                case 3:
                    // 180 rotate left
                    ctx.translate(width, height);
                    ctx.rotate(Math.PI);
                    break;

                case 6:
                    // 90 rotate right
                    ctx.rotate(0.5 * Math.PI);
                    ctx.translate(0, -height);
                    break;

                case 8:
                    // 90 rotate left
                    ctx.rotate(-0.5 * Math.PI);
                    ctx.translate(-width, 0);
                    break;
                default:
                    break;
            }

            // 铺底色
            ctx.fillStyle = "#fff";
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            //如果图片像素大于100万则使用瓦片绘制
            var count;
            if ((count = width * height / 1000000) > 1) {
                count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片

                // 计算每块瓦片的宽和高
                var nw = ~~(width / count);
                var nh = ~~(height / count);

                tCanvas.width = nw;
                tCanvas.height = nh;

                for (var i = 0; i < count; i++) {
                    for (var j = 0; j < count; j++) {
                        tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);

                        ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                    }
                }
            } else {
                ctx.drawImage(img, 0, 0, width, height);
            }

            // var mpImg = new MegaPixImage(img);
            // mpImg.render(canvas, {
            //     maxWidth: 800,
            //     maxHeight: 1200,
            //     quality: 0.8,
            //     orientation: Orientation
            // });

            //进行压缩
            var ndata = canvas.toDataURL('image/jpeg', 0.4);


            console.log('压缩前：' + initSize);
            console.log('压缩后：' + ndata.length);
            console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");

            tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
            previewCb && previewCb(ndata);
            return ndata;
        }

        /**
         * base64转二进制对象
         * @param baseStr
         * @returns {*}
         */
        function transmitCode(baseStr) {
            var text = window.atob(baseStr.split(",")[1]);
            var buffer = new Uint8Array(text.length);
            for (var i = 0; i < text.length; i++) {
                buffer[i] = text.charCodeAt(i);
            }
            var blob = getBlob([buffer], file.type);

            /**
             * 获取blob对象的兼容性写法
             * @param buffer
             * @param format
             * @returns {*}
             */
            function getBlob(buffer, format) {
                try {
                    return new Blob(buffer, {type: format});
                } catch (e) {
                    var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
                    buffer.forEach(function (buf) {
                        bb.append(buf);
                    });
                    return bb.getBlob(format);
                }
            }

            return blob;
        }

    }
}

// 桥接方法
export function setupWebViewJavascriptBridge(callback) {
    //for android
    if (window.WebViewJavascriptBridge) {
        callback(WebViewJavascriptBridge)
    } else {
        document.addEventListener('WebViewJavascriptBridgeReady', function () {
            callback(WebViewJavascriptBridge)
        }, false);
    }

    //for ios
    if (window.WVJBCallbacks) {
        return window.WVJBCallbacks.push(callback);
    }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'https://__BRIDGE_LOADED__';// deal with https for ios
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function () {
        document.documentElement.removeChild(WVJBIframe)
    }, 0);
}

export function bridgeCallHandler(type,params,callback) {
    if(!params){params={}}
    setupWebViewJavascriptBridge(function (bridge) {
        // if (isAndroid()) {
        //     if (window.WVJBCallbacks) { //注册默认接收android回调函数,ios不能加
        //         bridge.init(function (message, responseCallback) {
        //             var data = {'Javascript Responds': 'Wee!'};
        //             responseCallback(data);
        //         })
        //     }
        // }
        bridge.callHandler("commonJsCallBack", {jumpType:type,...params}, function(data) {
            if(callback){
                callback(data)
            }
        })
    });
}